﻿Public Class frmDollarRoom
    Private da As New DSVaultingTableAdapters.ir_monthly_dollar_stocksTableAdapter
    Private dda As New DSVaultingTableAdapters.ir_dollar_stock_detailsTableAdapter
    Private m As Integer
    Private y As Integer
    Private totalAmount As Long
    Private room As Integer
    Private action As String
    Private actType As String() = {"INSERT", "UPDATE"}
    Private fmclose As Boolean = True
    Private dt As DataTable

    Private Sub frmIRBox_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        m = frmMonthYearPicker.uxMonthcbb.SelectedIndex
        y = Integer.Parse(frmMonthYearPicker.uxYearcbb.Text)
        room = frmDollarRoomslc.uxRoomCbx.SelectedValue

        '
        ' Set label title
        '
        uxTitleLbl.Text = "ទូប្រាក់ដុល្លារ " & frmDollarRoomslc.uxRoomCbx.Text & " (ខែ " & frmMonthYearPicker.getKHMonth(m) & " " & y & ")"

        If checkCurrentMonth() Then
            If frmLogin.UserRole = frmLogin.RoleAdmin Then
                action = actType(1)
            Else
                uxBoxDgv.Columns("WhitePack").ReadOnly = True
                uxSaveChangeBtn.Enabled = False
            End If
            dt = dda.GetAllData(room, m, y)
            uxBoxDgv.DataSource = dt
            uxTotalTbx.Text = FormatNumber(dt.Rows(0).Item("TOTAL_AMOUNT"), 0)
        Else
            If frmLogin.UserRole = frmLogin.RoleAdmin Or frmLogin.UserRole = frmLogin.RoleUser Then
                action = actType(0)
            Else
                uxBoxDgv.Columns("WhitePack").ReadOnly = True
                uxSaveChangeBtn.Enabled = False
            End If
            uxBoxDgv.DataSource = dda.GetDataSheetOnly
        End If

    End Sub

    Private Function updateNoteAmount(ByVal dgv As DataGridView, _
                                  ByVal fstCol As String, _
                                  ByVal sndCol As String, _
                                  ByVal amount As String) As Long
        Dim sum As Long
        Dim total As Long = 0
        Dim val As Long
        Dim qt20 As Long
        Dim i As Integer

        For i = 0 To dgv.Rows.Count - 1 Step 1
            Try
                val = If(IsNumeric(dgv.Rows(i).Cells(fstCol).Value), dgv.Rows(i).Cells(fstCol).Value, 0)
                qt20 = If(IsNumeric(dgv.Rows(i).Cells(sndCol).Value), dgv.Rows(i).Cells(sndCol).Value, 0)
                sum = (qt20 * 1000) * val
            Catch ex As Exception
                MsgBox("The value is too big!")
            End Try
            dgv.Rows(i).Cells(sndCol).Value = qt20
            dgv.Rows(i).Cells(amount).Value = sum
            total += sum
        Next
        dgv.Update()
        Return total
    End Function

    Private Sub uxBoxDgv_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles uxBoxDgv.CellEndEdit
        totalAmount = updateNoteAmount(uxBoxDgv, "NoteType", "WhitePack", "Amount")
        uxTotalTbx.Text = FormatNumber(totalAmount, 0)
    End Sub

    Private Sub uxSaveChangeBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxSaveChangeBtn.Click
        Dim sql As New ArrayList()
        Dim sheetStock As String = "ir_monthly_dollar_stocks"
        Dim detailStock As String = "ir_dollar_stock_details"

        If action = actType(0) Then
            Dim newID As Long = da.ScalarQueryNewID

            sql.Add("INSERT INTO " & sheetStock & " VALUES (" & newID & _
                        "," & room & _
                        "," & totalAmount & _
                        "," & m & "," & y & ")")

            For i As Integer = 0 To uxBoxDgv.RowCount - 1 Step 1
                sql.Add("INSERT INTO " & detailStock & " VALUES (" & newID & _
                        "," & uxBoxDgv.Rows(i).Cells("SHEET_ID").Value & _
                        "," & uxBoxDgv.Rows(i).Cells("WhitePack").Value & _
                        "," & uxBoxDgv.Rows(i).Cells("Amount").Value & _
                        ",NOW())")
            Next

        ElseIf action = actType(1) Then
            Dim id As Long = dt.Rows(0).Item("STOCK_ID")
            sql.Add("UPDATE " & sheetStock & " SET " & _
                    " TOTAL_AMOUNT =" & totalAmount & _
                    " WHERE STOCK_ID=" & id)
            sql.Add("DELETE FROM " & detailStock & " WHERE STOCK_ID=" & id)

            For i As Integer = 0 To uxBoxDgv.RowCount - 1 Step 1
                sql.Add("INSERT INTO " & detailStock & " VALUES (" & id & _
                        "," & uxBoxDgv.Rows(i).Cells("SHEET_ID").Value & _
                        "," & uxBoxDgv.Rows(i).Cells("WhitePack").Value & _
                        "," & uxBoxDgv.Rows(i).Cells("Amount").Value & _
                        ",NOW())")
            Next
        End If

        'Dim lg As New LogGenerator
        'Dim st As String = ""
        'For Each s As String In sql
        '    st += s & ";" & vbNewLine
        'Next
        'lg.writeLog(st)
        '
        ' Execute Batch Insert
        '
        If action = "" Then
            MsgBox("លោកអ្នកមិនមានសិទ្ធគ្រប់គ្រាន់ទេ!", MsgBoxStyle.Exclamation)
        Else
            If MsgBox("តើលោកអ្នកពិតជាចង់រក្សាទុកអ្វីដែលបានកែប្រែមែនទេ??", MsgBoxStyle.YesNo) = DialogResult.Yes Then
                If executeBatch(sql) Then
                    MsgBox("ទិន្នន័យត្រួវបានរក្សាទុក")
                Else
                    MsgBox(DbConnect.errMsg)
                End If
            End If
        End If
    End Sub

    Private Function checkCurrentMonth() As Boolean
        Dim val As Integer
        val = da.ScalarQuerySelectMY(m, y, room)

        If Not val = 0 Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Sub uxCancelBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxCancelBtn.Click
        fmclose = False
        If MsgBox("តើអ្នកពិតជាចង់ចាកចេញមែន រឺ ទេ?", MsgBoxStyle.YesNo) = DialogResult.Yes Then
            Me.Close()
            frmRoomSelecting.Enabled = True
        End If
    End Sub

    Private Sub frmDollarRoom_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        If fmclose = True Then
            If MsgBox("តើអ្នកពិតជាចង់ចាកចេញមែន រឺ ទេ?", MsgBoxStyle.YesNo) = DialogResult.Yes Then
                e.Cancel = False
                frmRoomSelecting.Enabled = True
            Else
                e.Cancel = True
            End If
        End If
    End Sub
End Class